package com.totoro.mongo.demo.group;

import com.mongodb.AggregationOutput;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by Niki on 2018/7/23 18:02
 */
@Service
public class GroupDemo {
    @Autowired
    MongoTemplate mongoTemplate;

    public void demo() {

//        Aggregation aggregation = new Aggregation();
//        mongoTemplate.aggregate()
        Set<String> onumberSet=new HashSet<String>();
        onumberSet.add("001");
        onumberSet.add("002");
        onumberSet.add("003");
        //过滤条件
        DBObject queryObject=new BasicDBObject("onumber", new BasicDBObject("$in",onumberSet));
        DBObject queryMatch=new BasicDBObject("$match",queryObject);
        //展开数组
        DBObject queryUnwind=new BasicDBObject("$unwind","$items");
        //分组统计
        DBObject groupObject=new BasicDBObject("_id",new BasicDBObject("ino","$items.ino"));
        groupObject.put("total", new BasicDBObject("$sum","$items.quantity"));
        DBObject  queryGroup=new BasicDBObject("$group",groupObject);
        //过滤条件
        DBObject finalizeMatch=new BasicDBObject("$match",new BasicDBObject("total",new BasicDBObject("$gt",1)));

        AggregationOutput output=mongoTemplate.getCollection("orders").aggregate(queryMatch,queryUnwind,queryGroup,finalizeMatch);
        for (Iterator<DBObject> iterator = output.results().iterator(); iterator.hasNext();) {
            DBObject obj =iterator.next();
            System.out.println(obj.toString());
        }

    }

    public void demo2() {
        Aggregation aggregation = Aggregation.newAggregation(Aggregation.match(Criteria.where("").is(1)),
                Aggregation.group("").avg("").as(""));

        mongoTemplate.aggregate(aggregation, "", BasicDBObject.class);
    }
}
